<template>
  <div class="layout">
    <Layout>
      <Header style="padding: 0px 0px; background-color: white">
        <Menu mode="horizontal" :theme="theme" style="display: flex;justify-content: space-between">
          <div style="display: flex">
            <div class="layout-logo"><img src="@/assets/logo-pinda.png" /></div>
            <div class="menu-show" :style="menuStyle" style="z-index: 9999">
              <Icon
                @click="collapsedSider" :class="rotateIcon" :style="{margin: '0 20px'}" type="md-menu" size="24"
              ></Icon>
            </div>
            <div class="layout-nav">
              <Menu
                mode="horizontal"
                :theme="theme"
                active-name="1"
                @on-select="handleSelect"
              >
                <MenuItem name="home" to="/index/home">
                  <i class="el-icon-s-home"></i>
                  首页
                </MenuItem>
                <MenuItem
                  :name="menu.id"
                  v-for="(menu, index) in parentMenu"
                  :key="index"
                >
                  <i :class="menu.icon"></i>
                  {{ menu.name }}
                </MenuItem>
              </Menu>
            </div>
          </div>




          <div style="display: flex">

            <div class="layout-avatar">
              <el-dropdown>
                <el-avatar
                  :size="40"
                  style="margin-top: 10px"
                  @error="errorHandler"
                >
                  <img width="100%" :src="useimg" :alt="useimg" />
                </el-avatar>
                <el-dropdown-menu slot="dropdown">
                  <a
                  ><el-dropdown-item @click.native="tiaozhuanxinxi"
                  >个人信息</el-dropdown-item
                  ></a
                  >
                  <a @click="logout"
                  ><el-dropdown-item>退出登录</el-dropdown-item></a
                  >
                </el-dropdown-menu>
              </el-dropdown>
            </div>
            <div class="layout-username" style="margin-left: 10px;margin-right: 60px">
            <span style="margin-bottom: 60%; font-size: 14px">{{
                usename
              }}</span>
            </div>

          </div>
        </Menu>
      </Header>
      <Layout>
        <Sider
          style="
            width: auto;
            min-width: auto;
            max-width: none;
            flex: none;
            background: rgb(255, 255, 255);
          "
          hide-trigger
          :style="{ background: '#fff' }"
        >
          <el-menu
            unique-opened
            router
            :default-active="this.$router.path"
            class="el-menu-vertical-demo"
            @open="handleOpen"
            @close="handleClose"
            :collapse="isCollapse"
            :style="menuStyle"
          >
            <el-submenu
              :index="index1 + ''"
              v-for="(parentMenu, index1) in parentMenusWithChildMenus"
              :key="parentMenu.id"
            >
              <template slot="title">
                <i :class="parentMenu.icon"></i>
                <span slot="title">{{ parentMenu.name }}</span>
              </template>
              <el-menu-item-group>
                <span slot="title">{{ parentMenu.name }}</span>
                <el-menu-item
                  :index="childMenu.path"
                  v-for="childMenu in parentMenu.childMenus"
                  :key="childMenu.id"
                  @click="clkMenu(parentMenu, childMenu)"
                  >{{ childMenu.name }}</el-menu-item
                >
              </el-menu-item-group>
            </el-submenu>
            <el-menu-item
              :index="parentMenu.path"
              v-for="parentMenu in parentMenusWithoutChildMenus"
              :key="parentMenu.id"
              @click="clkMenu(parentMenu)"
            >
              <i :class="parentMenu.icon"></i>
              <span slot="title">{{ parentMenu.name }}</span>
            </el-menu-item>
          </el-menu>
        </Sider>
        <Layout :style="{ padding: '0 24px 24px' }">
          <Breadcrumb :style="{ margin: '24px 0' }">
            <BreadcrumbItem>首页</BreadcrumbItem>
            <BreadcrumbItem
              v-for="(breadcrumbItem, index) in breadcrumbItems"
              :key="index"
              >{{ breadcrumbItem }}</BreadcrumbItem
            >
          </Breadcrumb>
          <Card>
            <div style="height: 74vh; overflow: auto">
              <router-view />
            </div>
          </Card>
        </Layout>
      </Layout>
    </Layout>
  </div>
</template>
<script>
export default {
  data() {
    return {
      breadcrumbItems: JSON.parse(sessionStorage.getItem("breadcrumbItems")),
      useimg: "",
      usename: "",
      theme: "light",
      isCollapse: false,
      Icon: "",
      menus: [],
      parentMenu: [],
      childMenu: [],
      menuStyle: {
        display: "none",
      },
      token: JSON.parse(sessionStorage.getItem("satoken")),
    };
  },
  created() {
    const loading = this.$loading({
      lock: true,
      text: "Loading",
      spinner: "el-icon-loading",
      background: "rgba(0, 0, 0, 0.7)",
    });
    this.findMenuByUserId(); //根据用户id查询具有的菜单
    this.findUserIdRole(); //根据用户编号查询用户拥有的角色
    this.findUserByIdResourceAll(); //根据用户id查询具有的权限资源列表
    loading.close();
    this.querylog();
  },
  computed: {
    parentMenusWithChildMenus() {
      return this.childMenu.filter((menu) => menu.childMenus.length > 0);
    },
    parentMenusWithoutChildMenus() {
      return this.childMenu.filter((menu) => menu.childMenus.length === 0);
    },
    rotateIcon () {
      return [
        'menu-icon',
        this.isCollapse ? 'rotate-icon' : ''
      ];
    },
    menuitemClasses () {
      return [
        'menu-item',
        this.isCollapse ? 'collapsed-menu' : ''
      ]
    }
  },
  methods: {
    collapsedSider () {
      this.isCollapse=!this.isCollapse;

    },
    querylog() {
      //根据编号查询头像和name
      var x = JSON.parse(sessionStorage.getItem("satoken"));

      this.axios
        .get("/api/auth/pd_auth_user/pd_auth_user/" + x.loginId)
        .then((res) => {
          console.log(res);
          this.useimg = res.data.data.avatar;
          this.usename = res.data.data.name;
          sessionStorage.setItem("user", JSON.stringify(res.data.data));
        })
        .catch((err) => {
          console.error(err);
        });
    },
    logout() {
      //退出登录
      this.$router.push("/");
      sessionStorage.removeItem("satoken");
    },
    tiaozhuanxinxi() {
      //个人信息
      this.$router.push("/index/personalinformation");
    },
    errorHandler() {
      //图片加载不出来时返回
      return true;
    },
    handleOpen(key, keyPath) {
      console.log(key, keyPath);
    },
    handleClose(key, keyPath) {
      console.log(key, keyPath);
    },
    /**
     * 根据用户id查询具有的菜单
     */
    async findMenuByUserId() {
      try {
        await fetch(
          "/api/authorization/menu/findMenuByUserId/" + this.token.loginId
        )
          .then((response) => response.json())
          .then((data) => {
            if (data.code == 200) {
              this.menus = data.data;
              sessionStorage.setItem("menus", JSON.stringify(data.data));
              data.data.forEach((element) => {
                if (element.parentId == 0) {
                  this.parentMenu.push(element);
                }
              });
              let id = sessionStorage.getItem("parentMenuId");
              if (id.length > 0) {
                this.handleSelect(id);
              }
              retuen;
            }
            if (data.code == 11012) {
              this.$message.error(data.msg);
              setTimeout(() => {
                sessionStorage.removeItem("satoken");
                this.$router.push("/");
              }, 3000);
            }
          });
      } catch (error) {}
    },
    /**
     * 根据父级id查询对应子级菜单
     * @param {*} id
     */
    handleSelect(id) {
      if (id == "home") {
        sessionStorage.removeItem("parentMenuId");
        this.menuStyle.display = "none";
        return;
      }
      let menu = [];
      this.menus.forEach((p1) => {
        if (id == p1.parentId) {
          var parentMenu = {
            component: p1.component,
            createTime: p1.createTime,
            createUser: p1.createUser,
            describes: p1.describes,
            icon: p1.icon,
            id: p1.id,
            isEnable: p1.isEnable,
            isPublic: p1.isPublic,
            menugroup: p1.menugroup,
            name: p1.name,
            parentId: p1.parentId,
            path: p1.path,
            sortValue: p1.sortValue,
            updateTime: p1.updateTime,
            updateUser: p1.updateUser,
            childMenus: [],
          };
          this.menus.forEach((p2) => {
            if (p1.id == p2.parentId) {
              parentMenu.childMenus.push(p2);
            }
          });
          menu.push(parentMenu);
        }
      });
      this.childMenu = menu;
      sessionStorage.setItem("parentMenuId", id);
      this.menuStyle.display = "block";
    },
    /**
     * 根据用户编号查询用户拥有的角色
     */
    async findUserIdRole() {
      try {
        await fetch("/authority/role/findUserIdRole/" + this.token.loginId)
          .then((response) => response.json())
          .then((data) => {
            if (data.code == 200) {
              sessionStorage.setItem("roles", JSON.stringify(data.data));
            }
          });
      } catch (error) {}
    },
    /**
     * 根据用户id查询具有的权限资源列表
     */
    async findUserByIdResourceAll() {
      try {
        await fetch(
          "/authority/resources/findUserByIdResourceAll/" + this.token.loginId
        )
          .then((response) => response.json())
          .then((data) => {
            if (data.code == 200) {
              sessionStorage.setItem("resources", JSON.stringify(data.data));
            }
          });
      } catch (error) {}
    },
    clkMenu(parentMenu, childMenu) {
      this.breadcrumbItems = [];
      let i = [];
      if (childMenu == null) {
        this.menus.forEach((m) => {
          if (m.id == parentMenu.parentId) {
            console.log(m);
            i = [m.name, parentMenu.name];
          }
        });
        // 存储新数据到sessionStorage
        sessionStorage.setItem("breadcrumbItems", JSON.stringify(i));
        this.breadcrumbItems = JSON.parse(
          sessionStorage.getItem("breadcrumbItems")
        );
      } else {
        this.menus.forEach((m) => {
          if (m.id == parentMenu.parentId) {
            console.log(m);
            i = [m.name, parentMenu.name, childMenu.name];
          }
        });
        // 存储新数据到sessionStorage
        sessionStorage.setItem("breadcrumbItems", JSON.stringify(i));
        this.breadcrumbItems = JSON.parse(
          sessionStorage.getItem("breadcrumbItems")
        );
      }
    },
  },
};
</script>

<style>
element.style {
  width: auto;
  min-width: auto;
  max-width: none;
  flex: none;
  background: none;
}

html,
body {
  margin: 0px 0px;
  padding: 0px 0px;
}

.el-menu-vertical-demo:not(.el-menu--collapse) {
  width: 200px;
  min-height: 400px;
}

.layout {
  height: 100vh;
  background: #f5f7f9;
  position: relative;
  overflow: hidden;
}

.layout-logo {
  width: 180px;
  height: 30px;
  background: #fff;
  border-radius: 3px;
  float: left;
  position: relative;
  top: 5px;
  left: 60px;
}

/*.menu-show {*/
/*  margin-left: 60px;*/
/*  float: left;*/
/*  position: relative;*/
/*}*/

/*.layout-avatar {*/
/*  margin-left: 40%;*/
/*}*/
.layout{
    border: 1px solid #d7dde4;
    background: #f5f7f9;
    position: relative;
    border-radius: 4px;
    overflow: hidden;
}
.layout .ivu-menu{
    z-index: 0
}
.layout-header-bar{
    background: #fff;
    box-shadow: 0 1px 1px rgba(0,0,0,.1);
}
.layout-logo-left{
    width: 90%;
    height: 30px;
    background: #5b6270;
    border-radius: 3px;
    margin: 15px auto;
}
.menu-icon{
    transition: all .3s;
}
.rotate-icon{
    transform: rotate(-90deg);
}


</style>
